import Taro from "@tarojs/taro";
import { computed } from "vue";

export const useboxingInfo = ({ state, dicMap, navigateTo }) => {
  const { boxingSizeType, boxingSizeCode, fullOrEmptyCode } = dicMap;

  const boxingData = [
    { label: "集装箱号", keyName: "boxingCode" },
    { label: "类型尺寸", keyName: "boxingSizeType", dic: boxingSizeType },
    { label: "来源", keyName: "boxingSourceCode", dic: boxingSizeCode },
    {
      label: "重箱/空箱",
      keyName: "fullOrEmptyCode",
      dic: fullOrEmptyCode,
      hide: () => !state.truckPayloadType.isHeavyCar,
    },
    { label: "自重(KG)", keyName: "boxingWeight" },
    {
      label: "封志信息",
      valueCompute: (item) =>
        item.boxingSealed
          ? item.boxingSealedType +
            "/" +
            item.boxingSealed +
            "@" +
            item.boxingSealedName
          : "",
      hide: (item) => !state.truckPayloadType.isHeavyCar || !item.boxingSealed,
      // hide: (item) => !state.truckPayloadType.isHeavyCar,
    },
  ];

  const itemRender = (itemData, boxingIndex) => {
    const resultList = [];
    // 处理字段值
    const fetchValue = (item) => {
      if (item.valueCompute && typeof item.valueCompute === "function") {
        return item.valueCompute(itemData);
      } else if (item.dic) {
        return item.dic[itemData[item.keyName]] || itemData[item.keyName];
      } else {
        return itemData[item.keyName];
      }
    };
    boxingData.forEach((item) => {
      // 是否隐藏
      const isHide = item.hasOwnProperty("hide")
        ? typeof item.hide === "function"
          ? item.hide(itemData)
          : item.hide
        : false;

      !isHide &&
        resultList.push({
          label:
            item.keyName === "boxingCode"
              ? boxingIndex + 1 + "--" + item.label
              : item.label,
          value: fetchValue(item),
        });
    });

    return (
      <tz-view class="info-row">
        <tz-view
          class="box-info"
          onClick={() => handleDetail(itemData, boxingIndex)}
        >
          {resultList.map((item) => {
            return (
              <tz-view>
                <text>{item.label}</text>
                {item.value}
              </tz-view>
            );
          })}
        </tz-view>
        <tz-view class="del-box" onClick={() => handleDel(itemData.boxingCode)}>
          <tz-view class="icon-box">
            <tz-icon name="close"></tz-icon>
          </tz-view>
          删除
        </tz-view>
      </tz-view>
    );
  };

  const boxingInfoRender = computed(() => {
    return state.boxingInfo.map((item, index) => itemRender(item, index));
  });

  // 路由参数
  const navigateParams = computed(() => {
    const paramsData = {
      truckPayloadType: JSON.stringify(state.truckPayloadType),
      truckType: JSON.stringify(state.truckType), // 吨车 isTon  货柜车 isContainer
      trailerWeight: state.trayInfo ? state.trayInfo.trailerWeight : "", // 架重
      // 带已有的集装箱号以供判断是否重复
      boxingIds:
        state.boxingInfo && state.boxingInfo.length
          ? state.boxingInfo.map((item) => item.boxingCode)
          : [],
      // 带已有的类型尺寸以供判断是否存在超过限制的尺寸
      sizeTypes:
        state.boxingInfo && state.boxingInfo.length
          ? state.boxingInfo.map((item) => item.boxingSizeType)
          : [],
    };

    if (state.carInfo?.cacheSealedInfo) {
      paramsData.sealed = JSON.stringify(state.carInfo.cacheSealedInfo);
      // 车辆海关编码，集装箱页面调取按钮用到
      paramsData.truckLicenseCode = state.carInfo.truckLicenseCode;
    }
    return paramsData;
  });

  const handleAdd = () => {
    navigateTo({
      path: "/pages/subCN/truck/boxingInfo/index",
      query: navigateParams.value,
    });
  };
  const handleDetail = (data, boxingIndex) => {
    navigateTo({
      path: "/pages/subCN/truck/boxingInfo/index",
      query: {
        ...navigateParams.value,
        boxingInfo: JSON.stringify(data),
        boxingIndex,
      },
    });
  };
  const handleDel = (boxingCode) => {
    Taro.showModal({
      content: "确定删除该条记录吗?",
      confirmText: "确定",
      cancelText: "取消",
    }).then((res) => {
      if (res.confirm) {
        const targetIndex = state.boxingInfo.findIndex(
          (item) => item.boxingCode === boxingCode
        );
        state.boxingInfo.splice(targetIndex, 1);
      }
    });
  };

  // 存在一个大柜，隐藏新增集装箱按钮
  const isBigBox = computed(() => {
    if (state.boxingInfo && state.boxingInfo.length) {
      const sizeTypes = state.boxingInfo.map((item) => item.boxingSizeType);
      // 只要存在一个不为 2 的类型尺寸，就是有大柜
      return sizeTypes.some((item) => item && +item.substr(0, 1) !== 2);
    } else {
      return false;
    }
  });

  return () => (
    <>
      <tz-view
        class="title-content  margin-top20"
        v-show={state.carInfo && !state.truckPayloadType.isNoBoxEmptyCar}
      >
        <text>集装箱信息</text>
        {(!state.boxingInfo || state.boxingInfo.length < 2) && !isBigBox.value && (
          <tz-button type="primary" size="small" onClick={handleAdd}>
            添加集装箱
          </tz-button>
        )}
        {state.boxingInfo && (
          <tz-view class="cell-info">{boxingInfoRender.value}</tz-view>
        )}
      </tz-view>
    </>
  );
};
